package cn.jofei.netty.server;

import cn.jofei.netty.hadler.TCPServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;

import static cn.jofei.server.interf.ServerQueue.REG_TCP_CHANNELS;

/**
 * HTTP消息处理器
 *
 * @author Jofei Bao
 * @version ngbao v2.0
 * @date 2022年10月18日 11:29
 */
@Slf4j
public class SocketTCPServer extends SocketServer {

    private final int port;

    public SocketTCPServer(int port) {
        this.port = port;
    }

    @Override
    public void start() {
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(BOSS_GROUP, WORK_GROUP)
                .channel(NioServerSocketChannel.class)
                // 给 ServerSocketChannel 的配置 连接队列数配置 accept 处理的队列
                .option(ChannelOption.SO_BACKLOG, 256)
                // 给 SocketChannel 的配置
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel sc) throws Exception {
                        sc.pipeline()
                                // http 请求处理器
                                .addLast("TCP_Handler", new TCPServerHandler(port))
                        ;
                    }
                });
        bootstrap.bind(port).addListener((ChannelFutureListener) e -> {
            if (e.isSuccess()) {
                REG_TCP_CHANNELS.put(port, e.channel());
                log.info("创建 TCP 监听端口：{} 成功", port);
            } else {
                log.error("创建 TCP 监听端口异常", e.cause());
            }
        });
    }
}
